package com.qf.aspect;

import com.qf.annotation.MyLog;
import com.qf.exception.CustomerException;
import com.qf.mapper.LogMapper;
import com.qf.mapper.StudentMapper;
import com.qf.mapper.UserMapper;
import com.qf.pojo.Log;
import com.qf.pojo.Student;
import com.qf.pojo.User;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.UUID;

/**
 * @author zdl
 * @date 2025/2/18
 */
@Aspect
@Component
public class MyLogAspect {
    @Resource
    private LogMapper logMapper;
    @Before("@annotation(com.qf.annotation.MyLog)")
    public void mylog(JoinPoint joinPoint){
        //自定义注解中的值
        String log = getAnnoDesc(joinPoint);
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes( )).getRequest( );
        //获取远程主机ip
        String ip = request.getRemoteAddr();
        //name 写成一个死值
        /*User user = (User) request.getAttribute("login");
        if (user == null){
            throw  new CustomerException("30001","用户未登录");
        }*/
        Log log1 =new Log();
        log1.setLogTime(new Date());
        log1.setIp(ip);
        //log1.setName(user.getUsername());
        log1.setName("张三");
        log1.setLog(log);
        logMapper.insertLog(log1);

    }
    public static String getAnnoDesc(JoinPoint joinPoint){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获的目标方法对象
        Method method = signature.getMethod();
        MyLog myLog = method.getDeclaredAnnotation(MyLog.class);
        String value = myLog.value();
        return value;
    }
}
